<template>
  <div>
    <el-form label-width="120px">
      <!-- 职业标签信息 -->
      <el-form-item label="职业信息">
        <el-tag v-for="item in hasTagList" :key="item.id" size="small" class="gl_mr_5" :closable="hasTagList.length > 1" :disable-transitions="false" @close="deleteTag(item)">
          <span :key="item.id">{{ item.registerTagType.name }}</span>
        </el-tag>
        <el-button v-if="unHasTags.length" plain size="mini" @click="clickAddTag">{{ buttonTitle }}</el-button>
      </el-form-item>

      <el-dialog class="gl_dialog_TitleLine" title="选择角色标签" width="440px" :visible.sync="chooseTagVisible" :append-to-body="true" :close-on-click-modal="false" :close-on-press-escape="false">
        <el-checkbox-group v-model="chooseTagList">
          <el-row :gutter="20">
            <el-col v-for="item in unHasTags" :key="item.code" :span="6" class="gl_mb_15">
              <el-checkbox :label="item.code">{{ item.value }}</el-checkbox>
            </el-col>
          </el-row>
        </el-checkbox-group>
        <div slot="footer">
          <el-button size="mini" @click="chooseTagVisible = false">取 消</el-button>
          <el-button size="mini" type="primary" :loading="submitLoading" @click="submitAddTag">确 定</el-button>
        </div>
      </el-dialog>
    </el-form>
  </div>
</template>

<script>
import { mapState } from 'vuex';

import {
  api_GET_EventsManagementRegisterTag,
  api_DELETE_EventsManagementRegisterTagId,
  api_POST_EventsManagementRegisterTagTags
} from '@/extend/api/gameswaggerApi/app';

import {
  Api_GET_EventsManagementRegisterTagQO
} from '@/lib/form/game/swaggerForm';

export default {
  name: 'IdentityTag',
  props: {
    registerId: {
      type: String,
      required: true
    },
    buttonTitle: {
      type: String,
      default: '增加身份标签'
    }
  },
  data () {
    return {
      chooseTagVisible: false,
      chooseTagList: [], // 弹窗中被选择的标签
      hasTagList: [], // 用户拥有的标签
      unHasTagList: [], // 用户未拥有的标签
      doDelete: false, // 是否正在进行删除标签操作，因为网速慢得情况可能会将最后一个标签也移除，所以加上一层控制
      qo: new Api_GET_EventsManagementRegisterTagQO(),
      submitLoading: false
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      cache: state => state.dict.cache
    }),
    // 计算未拥有的身份标签
    unHasTags () {
      const _registerTags = this.hasTagList;
      if (_registerTags.length) {
        const _map = {};
        let _filterTags = [];
        _registerTags.forEach(item => {
          _map[item.registerTagType.code] = item;
        });

        if (this.dict.registerTagType) {
          _filterTags = this.dict.registerTagType.filter(item => !(item.code in _map));
        }
        return _filterTags;
      } else {
        return this.dict.registerTagType;
      }
    }
  },
  watch: {
    // 标签选择框是否显示
    chooseTagVisible(val) {
      if (!val) {
        this.chooseTagList = [];
      }
    }
  },
  mounted () {
    this.getRegisterTag();
  },
  methods: {
    // 点击增加身份标签按钮
    clickAddTag () {
      this.chooseTagVisible = true;
    },
    // 选择角色标签弹窗确定
    submitAddTag() {
      const tags = this.chooseTagList.map(item => {
        return {
          registerId: this.registerId,
          registerTagTypeCode: item
        };
      });
      if (tags.length) {
        this.submitLoading = true;
        api_POST_EventsManagementRegisterTagTags({ tags: tags })
          .then(
            res => {
              this.submitLoading = false;
              this.chooseTagVisible = false;
              this.getRegisterTag();
              this.$message({ type: 'success', message: '标签添加成功' });
            }
          );
      } else {
        this.$message({ type: 'warning', message: '请选择角色标签' });
      }
    },
    // 获取职业信息标签
    getRegisterTag() {
      this.qo.RegisterId = this.registerId;
      this.qo.IncludeRegisterTagType = true;
      api_GET_EventsManagementRegisterTag(this.qo)
        .then(
          res => {
            const _list = res.items || [];
            this.hasTagList = _list.sort((a, b) => a.registerTagType.sortOrder - b.registerTagType.sortOrder);
            this.doDelete = false;
          }
        )
        .catch(
          error => {
            console.log('查询标签列表失败', error);
          }
        );
    },
    // 删除身份信息标签
    deleteTag (tag) {
      if (this.doDelete) {
        // 如果正在进行删除操作，那么不能再进行删除，必须等待上一次执行得到结果
        return;
      }

      this.$confirm(`您确定要删除【${tag.registerTagType.name}】标签吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(
          () => {
            this.doDelete = true;
            api_DELETE_EventsManagementRegisterTagId(tag.id)
              .then(
                res => {
                  this.getRegisterTag();
                  this.$message({ type: 'success', message: '标签删除成功' });
                }
              )
              .catch(
                error => {
                  console.log('error', error);
                  this.doDelete = false;
                }
              );
          }
        )
        .catch(
          error => {
            console.log('error', error);
            this.doDelete = false;
          }
        );
    }
  }
};
</script>
